import os


def getyaml(jmhome, jmversion, basedir, filepath, savepath):
    commonTMP = r'''---
settings:
  env:
    Jmeter_Home: {0}   #Jmeter安装目录
    jmVersion: {1}   #Jmeter版本
    BASE_DIR: {2}   #项目目录
    Runtime: 30     #runtime 控制器测试时长
    Jtl_DIR: ${{BASE_DIR}}/jtl   #jtl保存目录
    testplans_DIR: {3} #jmx文件目录
  artifacts-dir: ${{BASE_DIR}}/TaurusRunlog/%Y-%m-%d-%H%M%S # path where to save artifacts, default is %Y-%m-%d_%H-%M-%S.%f #Taurus执行结果目录
  check-updates: false

modules:
  console:
    disable: true  # 测试时是否显示控制台，默认开启
  jmeter:
    path: ${{Jmeter_Home}}  #Jmeter安装目录
    version: ${{jmVersion}}  # minimal supported version of JMeter is 2.9
    force-ctg: true   # true by default
    detect-plugins: false
    csv-jtl-flags:  #修改csv保存结果参数，以便支持生成jmeter HTML报告
      saveAssertionResultsFailureMessage: true
      sentBytes: true

  #默认为false，true表示顺序执行，false表示并行执行
  local:
    sequential: true

#按照一下格式指定测试场景及测试时长，targettime表示响应时间指标，单位ms，可填可不填；
#hold-for表示线程组测试时长，与Runtime Controller同时存在时，该值优先；
#ramp-up表示线程加载时间，注意如果未hold-for，
#delay表示用例之间执行的间隔时间
#scenario表示场景名称，与下面scenario的参数配置对应    
execution:   
    '''

    executionTMP = r'''
- concurrency: 100
  targettime: 5000
  lastavgtime: 0 
  lasttps: 0 
  ramp-up: 10s
  hold-for: ${{Runtime}}s  
  60: 120s
  scenario: {0}
  distributed: []  
    '''
    scenarios = '''
#Runtime Controller：循环控制器，根据需求调整时间
#KPI Writer：Taurus默认保存的结果，这里调整为我们指定的目录及文件名称
#Errors Writer：Taurus默认保存的xml格式报错结果，这里调整为我们指定的目录及文件名称
#Res_Memory：对应jp@gc - PerfMon Metrics Collector插件监控内存，将插件名称改为Res_Memory
#Res_CPU：对应jp@gc - PerfMon Metrics Collector插件监控CPU，将插件名称改为Res_CPU    
scenarios:'''
    scenariosTMP = r'''
  {0}:
    script: ${{testplans_DIR}}/{0}.jmx
    modifications:
       set-prop:
        Runtime Controller>RunTime.seconds: ${{Runtime}}
        KPI Writer>filename: ${{Jtl_DIR}}/{0}_kpi.jtl   
        Errors Writer>filename: ${{Jtl_DIR}}/{0}_error.jtl  
        XMLJTL>filename: ${{Jtl_DIR}}/{0}.jtl
        Res_Memory>filename: ${{Jtl_DIR}}/{0}_memory.jtl
        Res_CPU>filename: ${{Jtl_DIR}}/{0}_cpu.jtl
        {0}>TransactionController.parent: false
       disable: [Res_Memory,Res_CPU]
    '''

    common = commonTMP.format(jmhome, jmversion, basedir, filepath)
    execution1 = ""
    scenarios1 = ""
    filenamelist = get_name(filepath, 'jmx')
    for index, f in enumerate(filenamelist):
        if index == 0:
            # 对第一个文件不包含 delay: 120s
            execution1 += executionTMP.format(f.split(".")[0]).replace("  delay: 120s/n", "")
        else:
            execution1 += executionTMP.format(f.split(".")[0])
        scenarios1 += scenariosTMP.format(f.split(".")[0])
    
    contents = (common + execution1 + scenarios.strip("") + scenarios1)
    contents = "".join([s for s in contents.splitlines(True) if s.strip()])
    with open(savepath, 'wb') as f:
        f.write(contents.encode('utf8'))
    print("文件已生成！")


def get_name(file_dir, file_type=''):  # 默认为文件夹下的所有文件
    lst = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if (file_type == ''):
                lst.append(file)
            else:
                if os.path.splitext(file)[1].replace(".", "") == str(file_type):  # 获取指定类型的文件名
                    lst.append(file)
    return lst

'''
if __name__ == '__main__':
    jmhome = r'D:/apache-jmeter-5.2.1/'  # Jmeter安装目录
    jmversion = '5.3'  # Jmeter版本
    basedir = r'E:/XCPTB/04TS'  # 项目目录
    filepath = r'E:/XCPTB/04TS/test'  # Jmeter测试脚本jmx文件存放目录
    getyaml(jmhome, jmversion, basedir, filepath)
'''